﻿using System;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Repository;
using Microsoft.SharePoint;
using Microsoft.SharePoint.IdentityModel;

namespace Eneta.Portal.Authentication.Live
{
    public class LiveAuthHandler : Page
    {
        protected string RedirUrl = "/default.aspx";
        protected BlogUserProfile bup;
        protected WindowsLiveLogin.User _user;

        // Initialize the WindowsLiveLogin module.
        private static WindowsLiveLogin wll = new WindowsLiveLogin(true);

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
        }
        #endregion

        private void Page_Load(object sender, EventArgs e)
        {
            Logger.LogInfo("Provider: " + Membership.Provider.Name);
            Logger.LogInfo("Web app port: " + Request.ServerVariables["HTTP_PORT"]);
            try
            {                
                _user = wll.ProcessLogin(Request.Form);

                if (_user != null)
                {
                    Logger.LogInfo("LiveAuthHandler.Page_Load(): Getting user " + _user.Id);
                    bup = BlogUserProfile.GetUser(_user.Id);
                }
                else
                {
                    Logger.LogInfo("LiveAuthHandler.Page_Load(): Signing user out");
                    FormsAuthentication.SignOut();
                }
            }
            catch (Exception ex)
            {
                Controls.Add(new LiteralControl(ex.ToString()));
                HttpContext.Current.Response.Write(ex);
                HttpContext.Current.Response.End();
            }
        }

        protected override void Render(HtmlTextWriter writer)
        {

            Logger.LogInfo("LiveAuthHandler.Render(): action is " + Request.QueryString["action"]);
            try
            {
                if (Request.QueryString["action"] == "logout")
                {
                    FormsAuthentication.SignOut();
                }
                else if (Request.QueryString["action"] == "clearcookie")
                {
                    Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
                    var gif = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAEALAAAAAABAAEAAAIBTAA7";

                    Page.Response.Clear();
                    Page.Response.ClearHeaders();
                    Page.Response.ContentType = "image/gif";
                    Page.Response.BinaryWrite(Convert.FromBase64String(gif));
                    Page.Response.Flush();
                }
                else if (Request.QueryString["action"] == "login")
                {
                    if (Request.QueryString["ReturnUrl"] != null)
                    {
                        RedirUrl = AuthConfig.LiveLoginUrl + Server.UrlEncode(Request.QueryString["ReturnUrl"]);
                    }
                    else if(Request.UrlReferrer != null)
                    {
                        RedirUrl = AuthConfig.LiveLoginUrl + Server.UrlEncode(Request.UrlReferrer.ToString());
                    }
                    else
                        RedirUrl = AuthConfig.LiveLoginUrl + Server.UrlEncode("/");

                    Logger.LogInfo("LiveAuthHandler: Login redirect: " + RedirUrl);
                }
                else
                {                    
                    if (bup == null)
                    {
                        if(_user == null)
                        {
                            Logger.LogWarning("LiveAuthHandler: Cannot find user after authentication");
                            Response.Redirect("/", false);
                            return;
                        }

                        BlogUserProfile.CreateUser(_user.Id, "");
                        bup = BlogUserProfile.GetUser(_user.Id);
                    }
                    
                    if (!bup.Locked)
                    {
                        Logger.LogInfo("LiveAuthHandler: profile exists");
                        Response.Cookies.Clear();
                        var result = SPClaimsUtility.AuthenticateFormsUser(Request.Url, bup.Id, "049430271a");
                        Logger.LogInfo("LiveAuthHandler: Claims authentication succeeded: " + result);
                        FormsAuthentication.SetAuthCookie(_user.Id, _user.UsePersistentCookie); // _user.UsePersistentCookie);
                        Logger.LogInfo("LiveAuthHandler: user is authenticated now");

                        //bup.PushProfile();
                        
                        if (string.IsNullOrEmpty(bup.Email))
                        {
                            RedirUrl = string.Format("/_layouts/Eneta.Portal.Register.aspx?Source={0}", _user.Context);
                        }                        
                        else
                        {
                            var profRep = new UserProfileRepository(SPContext.Current.Web);
                            var profile = profRep.GetUserProfileById(bup.ItemId);

                            if(string.IsNullOrEmpty(profile.Email) ||
                                string.IsNullOrEmpty(profile.FirstName) || 
                                string.IsNullOrEmpty(profile.LastName) ||
                                profile.Interests.Count == 0)
                            {

                                //RedirUrl = "/Lehed/editprofile.aspx?profileID=" + bup.ItemId + "&msg=missingflds";
                                RedirUrl = EnetaApplication.PortalProfileEditPageUrl + "?profileID=" + bup.ItemId + "&msg=missingflds";
                            }
                            else if (_user != null && _user.Context.Length > 0)
                            {
                                RedirUrl = _user.Context;
                            }
                        }
                    }
                    else
                    {
                        FormsAuthentication.SignOut();
                        RedirUrl = string.Format(AuthConfig.LockedUrl);
                    }
                }

                Logger.LogInfo("LiveAuthHandler.Render(): Final redirect url: " + RedirUrl);
                Logger.LogInfo("LiveAuthHandler.Render(): Detecting user");
                var usr = SPContext.Current.Web.CurrentUser;
                if(usr != null)
                {
                    Logger.LogInfo("LiveAuthHandler.Render(): User: " + usr.LoginName);
                }
                else
                {
                    Logger.LogInfo("LiveAuthHandler.Render(): User is null ");
                }
                Response.Redirect(RedirUrl,false);
            }
            catch (Exception ex)
            {
                Controls.Add(new LiteralControl(ex.ToString()));
                HttpContext.Current.Response.Write(ex);
                HttpContext.Current.Response.End();
            }
        }
    }

}
